package com.myorg.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.myorg.util.ConstantsToBeExternalized;
import com.myorg.util.Utility;

//TODO: Auto-wiring is not there yet.
public class AdminService {
	final Logger logger = LoggerFactory.getLogger(AdminService.class);

	public String testDrive(final int threadSize, final long fileSize, final String parentPath) {
		final List<File> files = new ArrayList<File>();
		for (int i = 0; i < threadSize; i++) {
			files.add(createTmpLocalFile(parentPath, fileSize));
		}

		return Utility.measureExecutionTime(new Runnable() {
			@Override
			public void run() {

				final CountDownLatch latch = new CountDownLatch(files.size());
				for (final File f : files) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								scanFile(f);
							} finally {
								latch.countDown();
							}
						}
					}).start();
				}
				try {
					latch.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				} finally {
					for (final File f : files) {
						f.delete();
					}
				}
			}
		});
	}

	private File createTmpLocalFile(String parentPath, long size) {
		try {
			File file = StringUtils.isEmpty(parentPath) ? new File("temp_test_file_" + System.currentTimeMillis()
					+ ".txt") : new File(parentPath + "/temp_test_file_" + System.currentTimeMillis() + ".txt");
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			for (long l = 0; l < size; l++) {
				if (l % 10 == 0) {
					bw.write("\n");
				} else {
					bw.write("0");
				}
			}
			bw.close();
			logger.info("Created local file : " + file.getName() + ", " + file.length());
			return file;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	private void scanFile(File f) {
		try {
			logger.info("Scanning file: " + f.getAbsolutePath());
			BufferedReader in = new BufferedReader(new FileReader(f),
					ConstantsToBeExternalized.DEFAULT_HDFS_READ_BUFFER_SIZE);
			long size = 0L;

			int c = in.read();
			while (c != -1) {
				size++;
				c = in.read();
			}

			logger.info("Scaned local file " + f.getName() + " : " + size);

			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
